package subtitle

import (
	"fmt"
	"os"

	"github.com/gogf/gf/v2/encoding/gjson"

	"beesoft.ink/application/media/app/helper/helper"
	"beesoft.ink/application/media/app/helper/storage"
)

func ToSrt(content string) (string, error) {
	var result string

	var srtItems []SrtItem
	if err := gjson.DecodeTo(content, &srtItems); err != nil {
		return result, err
	}

	// var lastEnd int64 = 0
	//
	// for i, srt := range srtItems {
	// 	if lastEnd > srt.Start {
	// 		delta := lastEnd - srt.Start
	// 		if delta < 500 {
	// 			delta = delta / 2
	// 			srt.Start = srt.Start - delta
	// 			srtItems[i-1].End = srt.Start
	// 			lastEnd = srt.End
	// 		}
	// 	}
	// 	lastEnd = srt.End
	// }

	for i, srtItem := range srtItems {
		startTime := helper.HmsMillisString(srtItem.Start)
		endTime := helper.HmsMillisString(srtItem.End)
		result += fmt.Sprintf("%d\n%s --> %s\n%s\n", i+1, startTime, endTime, srtItem.Text)
	}

	return result, nil
}
func ToSrtFile(fileName, content string) error {
	content, err := ToSrt(content)
	if err != nil {
		return err
	}

	directory := storage.File.GetStorageDir("temp")
	if _, err := os.Stat(directory); os.IsNotExist(err) {
		err = os.Mkdir(directory, 0755)
		if err != nil {
			return err
		}
	}

	path := fmt.Sprintf("%s/%s", directory, fileName)
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	defer func() {
		_ = file.Close()
	}()

	_, err = file.WriteString(content)
	// err = ioutil.WriteFile(path, []byte(content), 0644)
	if err != nil {
		return err
	}

	return nil
}
